<template>
  <div class="wrapper">
    <!-- <a-tabs :selectTabKey="selectTabKey" @change="changeActive" class="tabList" :style="{'width':widthStyle}">
      <a-tab-pane key="1">
        <span class="tab-title" slot="tab">
          {{$t('todoPage.tabName.todoProcess')}}
          <div class="taskNum" v-if="parseInt(countList.toDoProcessNum) > 0">{{ countList.toDoProcessNum }}</div>
        </span>
      </a-tab-pane>
      <a-tab-pane key="2">
        <span class="tab-title" slot="tab">
          {{$t('todoPage.tabName.tasksToBePerformed')}}
          <div class="taskNum" v-if="parseInt(countList.outTask) > 0">{{ countList.outTask }}</div>
        </span>
      </a-tab-pane>
      <a-tab-pane key="3">
        <span class="tab-title" slot="tab">
          {{$t('todoPage.tabName.tasksToBeReviewed')}}
          <div class="taskNum" v-if="parseInt(countList.tasksToBeReviewed) > 0">{{ countList.tasksToBeReviewed }}</div>
        </span>
      </a-tab-pane>
    </a-tabs> -->
    <tabs 
    :defaultTagId="selectTabKey" 
    :tabPaneData="tabPaneData" 
    :fieldData="fieldData" 
    :custom="false" 
    @change="tabCallBack($event)"></tabs>
    <div class="tableItem" v-if="fromName !== 'protal'">
      <a-row>
        <a-col :span="6">
          <span class="tabItemTitle" v-if="selectTabKey == '1'">{{$t('todoPage.processList')}}</span> 
          <span class="tabItemTitle" v-else-if="selectTabKey == '2'">
            <a-button type="primary" @click="showApplyComplete(1)">{{$t('todoPage.applicationCompleted')}}</a-button>
          </span>
          <span class="tabItemTitle" v-else-if="selectTabKey == '3'">{{$t('todoPage.auditTaskList')}}</span>
          <div>
            <!--动态显示抽屉（单条/多条）抽屉打开不能再次刷新方法 在父组件添加v-if-->
            <component :is="applyCom" :drawerVisible_p="drawVisible" v-if="drawVisible" :oid="oid"
              :assignmentOid="assignmentOid"
              :taskName="taskName"
              :dataStatus="dataStatus"
              :isHaveDelive="isHaveDelive"
              :action="taskAction"
              @closeDraw="closeApplyComplete"
              :dataObj="carryTaskValue"
              ></component>
          </div>
        </a-col>
        <a-col  :span="18">
          <div class="inputBox">
            <a-input-search placeholder="请输入搜索关键词" style="width: 420px" v-model="searchInput['v'+selectTabKey]" :allowClear="true" @search="searchRes"/>
          </div>
        </a-col>
      </a-row>
    </div>
    <div class="portalTitle" v-else>
      <a-row>
        <a-col :span="6">
          <span class="tabItemTitle" v-if="selectTabKey == '2'">
            <a-button type="primary">{{$t('todoPage.applicationCompleted')}}</a-button>
          </span>
        </a-col>
      </a-row>
    </div>

    <div class="table">
      <common-table
        :fromName="fromName"
        ref="commonTable"
        :columns="columns"
        :tableData="dataSource"
        :selectType="'checkbox'"
        @routerPage="routerPage"
        @routerActionPage="routerActionPage"
        :data-row-key="tableKey"
        :isRowsSelectVisible="selectTabKey==2?true:false"
        :scrollY="widthStyle=='66%'? 300 : 'calc(100vh - 380px)'"
      ></common-table>
    </div>
  </div>
</template>
<script>
import commonTable from "@/components/common/commonTable";
import tabs from "@/components/tabs/tabs"
import { closeSingleTabs } from '@/api/common'
import applyCompleteOnce from "@views/plmHomePage/toDoPage/applyCompleteOnce";
import applyCompleteMore from "@views/plmHomePage/toDoPage/applyCompleteMore";
import { tabColumnFirst,tabDataFirst,tabColumnSecond,tabDataSecond,tabColumnThird,tabDataThird } from './dataBase'

import { getWorkItemList } from "@/apiTest/todo.js"
import _ from 'lodash'
export default {
  components: {
    tabs,
    commonTable,
    applyCompleteOnce,
    applyCompleteMore
  },
  props:{
    widthStyle:{
      type:String,
      default:'84%'
    },
    tabCategoryList: {
      type: Array,
      default: () => []
    },
    fromName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectTabKey:'1',
      fieldData: {name: 'name', enName: 'tagEnName', id: 'id', num: 'num'},
      countList:{
        toDoProcessNum:0,
        outTask:0,
        tasksToBeReviewed:0,
      },
      columns:[],
      dataSource: [],
      dataSourceCopy : [],
      selectedRows: [],
      tableKey:'',
      pageCount: 10, // 每页显示条数
      startIndex: 0, // 起始页第一条
      searchInput:{
        v1:'',
        v2:'',
        v3:''
      },
      tabPaneData: [],
      drawVisible:false,
      applyCom: "applyCompleteOnce", //抽屉名称
      assignmentOid:'',
      taskName: "产品定义评审-test", //任务名称
      dataStatus: "已完成", //数据状态
      isHaveDelive: "否", //是否有交付物
      taskAction: "执行任务", //点击表格动作
      carryTaskValue: {}, //执行任务传参
      oid:'',
    };
  },
  watch:{
    tabCategoryList(val) {
      this.tabPaneData = val
      this.standardColumns();
    }
  },

  mounted(){
    this.$store.commit("setTodoProcessNum", tabDataFirst.length);
    this.$store.commit("setOutTask", tabDataSecond.length);
    this.$store.commit("setToReviewedTask", tabDataThird.length);
    this.standardColumns();
  },
  methods: {
    standardColumns(){
      if (this.tabPaneData.length <= 0 ) {
        this.tabPaneData = [
          {id: "1", name: "待办流程", num: 0, rank: 1, tagEnName: "To do process"},
          {id: "2", name: "待执行任务", num: 0, rank: 2, tagEnName: "Tasks to be performed"},
          {id: "3", name: "待审核任务", num: 0, rank: 3, tagEnName: "Tasks to be reviewed"},
        ]
      } else { 
        this.widthStyle=='66%'? this.$refs.commonTable.pagination.pageSize = 5 : this.$refs.commonTable.pagination.pageSize = 10
      }
      this.columns = tabColumnFirst;
      if(this.selectTabKey==1){
        // this.columns = tabColumnFirst;
        // if(sessionStorage.getItem('changeItem')){
        //   let arr = JSON.parse(sessionStorage.getItem('changeItem'));
        //   arr = arr.map(item=>{
        //     item['operation'] = '初审';
        //     item["pbo.state"] = "正在审阅";
        //     item["pbo.localizedType"] = "项目变更请求";
        //     item["workItem.status"] = "潜在的";
        //     item["process.container"] = "重品项目";
        //     item['workItem.theme'] = item.name;
        //     item['process.name'] = `PIProjectChangeRequestWf_${item.number}--${item.name}`;
        //     item['workItem.theme'] = item.name;
        //     item['workItem.thePersistInfo.createStamp'] = item.createDate;
        //     item['activityOid'] = item.name+"OR:wt.workflow.work.WfAssignedActivity:27040199664";
        //     item['pboOid'] = item.name+"OR:com.pisx.pmgt.change.PIProjectChangeRequest:27040199664";
        //     return item;
        //   })
        //   this.dataSource = [];
        //   this.dataSource = arr.concat(tabDataFirst)
        // }else{
        //   this.dataSource = tabDataFirst;
        // }
        // this.countList.toDoProcessNum = this.dataSource.length;
        let parms = {
          // "userId": "wcadmin",
          count: 10,
          pagingSearch: true,
          startIndex: 0,
          status: "NOT_COMPLETED",
        };

        getWorkItemList(parms).then(res => {
          if (res.data && res.data.data && res.data.success) {
            this.dataSource = res.data.data
            this.tabPaneData[this.selectTabKey-1].num = this.dataSource.length;
          }
        })
      }else if(this.selectTabKey==2){
        this.columns = tabColumnSecond;
        this.dataSource = tabDataSecond;
        this.countList.outTask = this.dataSource.length;
      }else if(this.selectTabKey==3){
        this.columns = tabColumnThird;
        this.dataSource = tabDataThird;
        this.countList.tasksToBeReviewed = this.dataSource.length;
      }
      this.columns = this.columns.map(item=>{
        item.width = 200;
        return item
      })
      this.tableKey = "activityOid";
      this.dataSourceCopy = this.dataSource;
      this.searchRes();
    },
    changeActive(key) {
      this.selectTabKey = key;
      this.standardColumns();
    },
    tabCallBack(tabKey, status) {
      this.dataSource = []
      this.spinning = true
      this.selectTabKey = tabKey
      this.standardColumns();
    },
    //表格选中项
    onSelectChange(id,row){
      this.selectedRows = row
    },
    searchRes(){
      let arr = _.clone(this.dataSourceCopy);
      if(this.searchInput){
        this.dataSource = arr.filter(item=>{
          item.str = JSON.stringify(item)
          return item.str.indexOf(this.searchInput['v'+this.selectTabKey])!=-1
        })
      }else{
        this.dataSource = arr
      }
    },
    // 第一个tab，点击“操作”跳转 || 点击第二个tab中任务名称显示的抽屉
    routerPage(val) {
      const projectObj = {
        projectName: val['process.container'],
        projectType:  val['process.project.type']
      }
      sessionStorage.setItem("ProjectObj", JSON.stringify(projectObj))
      sessionStorage.setItem("fromRouteName", "todoPageList")
      /* session值项目名称--头部  开始  */
      if (val.pboOid && val.pboOid.indexOf("Planning") == -1) {
        let str = "";
        if (this.selectTabKey === "1") {
          str = val["process.container.oid"];
        } else {
          str = val.projectOid;
        }
        if(str){    //仿真委托书不属于项目里面的，所有委托书的流程里没有项目的oid
          sessionStorage.setItem("oid", str && str.substring(str.lastIndexOf(":") + 1));
        }
      }
      sessionStorage.setItem('todoInfoData', JSON.stringify(val))
      /* session值项目名称--头部  结束   */
      if (this.selectTabKey == "1") {
        this.$router.push({
          path: "/single/fileSingle/fileStart",
        });

        return

        if (
          val["pbo.localizedType"].indexOf("文档") > -1 ||
          val["pboOid"].indexOf("WTDocument") != -1
        ) {
          //待办流程点击操作跳转至流程交付物页面（操作界面）
          let fileSingleTableItem_s = {
            oid: val['workItemOid'],//流程oid
            singleOid:val['pboOid'],  //文档Oid
            workItemName: val['operation'],//流程节点名称
            state: val['pbo.state'],//流程状态
            workItemState: val['workItem.status']//交付物状况
          }
          sessionStorage.setItem("fileSingleTableItem", JSON.stringify(fileSingleTableItem_s))
          this.$store.commit('SET_PROJECT_FILE_TITLE', '')
          closeSingleTabs()
          this.$router.push({
            path: "/single/fileSingle/examineProject",
          });
        } else if (val["pboOid"].indexOf("ProjectKnotItemBook") != -1) {
          /**验收表流程入口 */
          let fileSingleTableItem_s = {
            oid: val['workItemOid'],//流程oid
            workItemName: val['operation'],//流程节点名称
            state: val['pbo.state'],//流程状态
            pboOid: val['pboOid'],//验收表id
            workItemState: val['workItem.status'],//验收表状况
            processName: val['workItem.theme']
          }
          sessionStorage.setItem("acceptListData", JSON.stringify(fileSingleTableItem_s))
          let typeObj = {
            type: 'process',
            acceptId: val['pboOid']
          }
          sessionStorage.setItem('processAcceptInfo', JSON.stringify(typeObj))
          // sessionStorage.setItem('acceptProcessInfo', JSON.stringify(fileSingleTableItem_s))
          closeSingleTabs()
          this.$router.push({
            path: '/single/projectAcceptList/porjectAcceptProcess',
            query: {
              isJump: true
            },
          })
        } else if (val['process.name'].startsWith("QIS")) {
          closeSingleTabs()
          this.goRouterQis(val.workItemOid)
        } else if (val.pboOid.indexOf("sany.pmgt.tdm.model") != -1) {
          this.toBookRouterTDM(val)
        } else if (val["pboOid"].indexOf("ProjectIssue") != -1) {
          sessionStorage.setItem('questionItem', JSON.stringify(val))
          closeSingleTabs()
          if(val.operation === "修改"){
            this.$router.push({
              path: '/single/questionSingle/editQuestion',
            })
          }else{
            this.$router.push({
              path: '/single/questionSingle/examineQuestion',
            })
          }
        } else if (val["pboOid"].indexOf("ProjectRisk") != -1) {
          sessionStorage.setItem('riskItem', JSON.stringify(val))
          closeSingleTabs()
          if(val.operation === "修改"){
              this.$router.push({
                path: '/single/riskSingle/examineRiskBack',
              })
          }else{
              this.$router.push({
                path: '/single/riskSingle/examineRisk',
              })
          }
        } else if (val["pboOid"].indexOf("RMTask") != -1) { //需求关联（需求任务单流程）
          sessionStorage.setItem('demandItem', JSON.stringify(val))
          closeSingleTabs()
          if(val.operation === "需求关联" || val.operation === "移除需求关联的项目" || val.operation === "更改需求任务单"){
              this.$router.push({
                // path: '/single/demandSingle/examineDemand',
                path: '/toDoPage/examineDemand',
              })
          }
        } else if (val["pboOid"].indexOf("PPMSubPlan") != -1) { //需求关联（子规划流程）   //&& val['pbo.localizedType'].indexOf('子规划')
          sessionStorage.setItem('ppmdemandItem', JSON.stringify(val))
          closeSingleTabs()
          if(val.operation === "需求关联" || val.operation === "移除需求关联的项目"){
              this.$router.push({
                // path: '/single/demandSingle/childPlan',
                path: '/toDoPage/childPlan',
              })
          }
        } else if (val.pboOid.indexOf("Planning") != -1) {
          closeSingleTabs()
          this.toBookRouter(val)
        } else if (val.pboOid.indexOf("EntrustBook") != -1) {
          if (val['toPlm'] === "true") {
            this.$message.warn('非项目仿真委托需去PLM系统处理')
            return false
          }
          console.log('仿真委托书流程信息',val);
          this.toBookRouterSDM(val);      //SDM仿真委托书
        } else if (val["pbo.localizedType"].indexOf('评审') > -1 || val["pboOid"].indexOf("PIReview") != -1){
          sessionStorage.setItem('reviewId',val.pboOid)
          sessionStorage.setItem("workItemOid",val.workItemOid)
          sessionStorage.setItem("techProcessName",val['process.name'])
          sessionStorage.setItem("craftOperation",val.operation) 
          closeSingleTabs()
          if(val.operation === "审阅"){
            this.$router.push({
              path: "/single/reviewSingle/selfCheck",
            });
          } else if (val.operation === "修改完善") {
            this.$router.push({
              path: "/single/reviewSingle/modifyPerfect",
            });
          } else if (val.operation === "修改") {
            this.$router.push({
              path: "/single/reviewSingle/rejectModify",
            });
          } else {
            sessionStorage.setItem("operation", val.operation)
            this.$router.push({
              path: '/single/reviewSingle/PMOReview',    
              // query: {
              //   operation: val.operation
              // }     
            })
          }
        } else if (val['process.name'].indexOf('SNProjectCloseWF') != -1) {
          //项目关闭 SNProjectCloseWF    process.name
          sessionStorage.setItem("closedData", JSON.stringify(val));
          closeSingleTabs()
          this.$router.push({
            path: "/single/fileSingle/closeExamine",
          });
        } else if (val["pbo.localizedType"].indexOf("项目变更") > -1 || val["pboOid"].indexOf("PIProjectChangeRequest") != -1 ) { //项目变更
          sessionStorage.setItem("changeAlterationData", JSON.stringify(val));
          closeSingleTabs()
          if(val.operation === "修改"){
            let str = val['process.container.oid'];
            sessionStorage.setItem("oid", str.substring(str.lastIndexOf(":") + 1));
            this.$router.push({
              path: "/single/projectAlteration/editAlteration",
            });
          }else{
            sessionStorage.setItem('changeUndoVal',JSON.stringify(val))
            this.$router.push({
              path: "/single/projectAlteration/changeAlteration",
            });
          }
        } else {
          // this.$message.info("暂不支持该流程操作！");
          window.open(val['process.name.url'])
        }
        
      } else if (this.selectTabKey == "2") {
        // this.tableKey = "activityOid"
        this.oid = val.activityOid;
        this.assignmentOid = val.assignmentOid;
        this.taskName = val["activity.name"];
        this.dataStatus = val["assignment.plannableStatus"];
        this.isHaveDelive = val["hasPIDeliverable"];
        this.taskAction = "";
        // this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
        this.showApplyComplete(5); //执行任务 (zj)
      } else if (this.selectTabKey == "3") {
        // this.tableKey = "activityOid"
        this.oid = val.activityOid;
        this.assignmentOid = val.assignmentOid;
        this.taskName = val["activity.name"];
        this.dataStatus = val["assignment.plannableStatus"];
        this.isHaveDelive = val["hasPIDeliverable"];
        this.taskAction = "";
        // this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
        this.showApplyComplete(4); //审核任务
      }
    },
    //展开抽屉
    showApplyComplete(num) {
      switch (num) {
        case 1:
          if (this.$store.state.selectedTableData.length === 1) { // 当tab2中只选中一个任务，点击申请完成
            this.applyCom = "applyCompleteOnce";
            this.assignmentOid =
              this.$store.state.selectedTableData[0].assignmentOid;
          } else if (this.$store.state.selectedTableData.length > 1) { // 多个任务，点击申请完成
            this.applyCom = "applyCompleteMore";
          } else {
            this.$message.error("请最少选择一项任务！");
            this.applyCom = "";
          }
          break;
        case 2:
          this.applyCom = "deliverableList";
          break;
        case 3:
          this.applyCom = "carryTask";
          break;
        case 4:
          this.applyCom = "examineTask";
          break;
        case 5:
          this.applyCom = "carryTaskNoDo";
          break;
      }
      this.drawVisible = true;
      // this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
    },
    //关闭抽屉
    closeApplyComplete() {
      this.drawVisible = false;
    },
    // 点击第二个和第三个tab切换“操作”跳转
    routerActionPage(val) {
      sessionStorage.setItem("fromRouteName", "todoPageList")
      /* session值项目名称--头部  开始  */
      if (val.pboOid && val.pboOid.indexOf("Planning") == -1) {
        let str = "";
        if (this.selectTabKey === "1") {
          str = val["process.container.oid"];
        } else {
          str = val.projectOid;
        }
        sessionStorage.setItem("oid", str && str.substring(str.lastIndexOf(":") + 1));
      }
      /* session值项目名称--头部  结束   */
      if (this.selectTabKey == "1") {
        if (
          val["pbo.localizedType"].indexOf("文档") > -1 ||
          val["pbo.localizedType"].indexOf("PM") > -1 ||
          val["pboOid"].indexOf("WTDocument") != -1
        ) {
          //待办流程点击操作跳转至流程交付物页面（操作界面）
          let fileSingleTableItem_s = {
            oid: val["workItemOid"], //流程oid
            workItemName: val["operation"], //流程节点名称
            state: val["pbo.state"], //流程状态
            // pboOid: val['pboOid'],//交付物id
            workItemState: val['workItem.status']//交付物状况
          }
          sessionStorage.setItem("fileSingleTableItem", JSON.stringify(fileSingleTableItem_s))
          this.$store.commit('SET_PROJECT_FILE_TITLE', '')
          closeSingleTabs()
          this.$router.push({
            path: "/single/fileSingle/examineProject",
          });
        } else {
          this.$message.info("暂不支持该流程操作！");
        }
      } else if (this.selectTabKey == "2") {
        this.carryTaskValue = val
        sessionStorage.setItem('projectOid',JSON.stringify(val.projectOid))
        // this.tableKey = "activityOid"
        this.oid = val.activityOid;
        this.assignmentOid = val.assignmentOid;
        this.taskName = val["activity.name"];
        this.dataStatus = val["assignment.plannableStatus"];
        this.isHaveDelive = val["hasPIDeliverable"];
        this.taskAction = "执行任务";
        // this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
        let str = val.projectOid
        sessionStorage.setItem('oid', str.substring(str.lastIndexOf(":") + 1));
        this.showApplyComplete(3); //执行任务
      } else if (this.selectTabKey == "3") {
        // this.tableKey = "activityOid"
        this.oid = val.activityOid;
        this.assignmentOid = val.assignmentOid;
        this.taskName = val["activity.name"];
        this.dataStatus = val["assignment.plannableStatus"];
        this.isHaveDelive = val["hasPIDeliverable"];
        this.taskAction = "审核任务";
        // this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
        this.showApplyComplete(4); //审核任务
      }
    },
  },
};
</script>
<style lang="less" scoped>
  .wrapper{
    width: 100%;
    height: 100%;
    background: #fff;
    padding: 0px 20px;
    overflow: hidden;
    position: relative;
    .tabList{
      position: fixed;
      width: 80%;
      height: 70px;
      background: #fff;
      z-index: 1;
    }
    .tableItem{
      //  margin-top: 70px;
       margin-bottom: 10px;
       color: #000;
       font-size: 18px;
    }
    .portalTitle {
      position: absolute;
      z-index: 999;
      right: 0;
      top: 0;
    }
    .inputBox{
      float: right;
    }
    .tab-title {
      width: 100%;
      height: 30px;
      //background-color: green;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .taskNum {
      min-width: 18px;
      height: 18px;
      border-radius: 100px;
      background-color: #f5222d;
      margin: -15px 0px 0px 5px;
      padding: 0px 3px 0px 3px;
      line-height: 18px;
      color: #ffffff;
      font-size: 12px;
      text-align: center;
    }
  }

</style>
